package com.efounder.chat.utils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import static com.efounder.chat.http.GetHttpUtil.ROOTURL;
import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * Created by cherise on 2016/9/14.
 */

//生成群组名，群组新增群成员，群成员退出时，生成新的群组名
public class GroupNameUtil {

    /**
     * 查询群组中人员的昵称，顺序-- 我设置的，用户自己设置的，好友昵称，用户昵称
     *
     * @param groupId
     * @param userId
     * @param
     * @return
     */
    public static User getGroupUser(int groupId, int userId) {

        User user = WeChatDBManager.getInstance().getOneFriendById(userId);
        if (user.getNickName().equals(String.valueOf(userId))) {
            //说明不是好友
            user = WeChatDBManager.getInstance().getOneUserById(userId);
        }
        User tempUser = WeChatDBManager.getInstance().getGroupUserInfo(groupId, userId);
        if (tempUser != null) {
            user.setOwnGroupRemark(tempUser.getOwnGroupRemark());
            user.setOtherGroupRemark(tempUser.getOtherGroupRemark());
            user.setGroupUserType(tempUser.getGroupUserType());
        }


        return user;
    }

    public static String getGroupUserName(User user) {

        String name = "";
        if (user != null) {
            if (user.getOtherGroupRemark() != null && !user.getOtherGroupRemark().equals("")) {
                name = user.getOtherGroupRemark();
            } else if (user.getOwnGroupRemark() != null && !user.getOwnGroupRemark().equals("")) {
                name = user.getOwnGroupRemark();
            } else if (user.getReMark() != null && !user.getReMark().equals("")) {
                name = user.getReMark();
            } else {
                name = user.getNickName();
                if (name == null || "".equals(name)) {
                    name = user.getId() + "";
                }
            }

        }
        return name;
    }

    /**
     * 群组中人员的昵称，顺序-- 我设置的，用户自己设置的，好友昵称，用户昵称
     *
     * @param user
     * @return
     */
    public static String getGroupUserNameHU(User user) {
        if (user == null) {
            return "";
        }
        if (user.getOwnGroupRemark() != null && !user.getOwnGroupRemark().equals("")) {
            return user.getOwnGroupRemark();
        }
        if (user.getOtherGroupRemark() != null && !user.getOtherGroupRemark().equals("")) {
            return user.getOtherGroupRemark();
        }
        if (user.getReMark() != null && !user.getReMark().equals("")) {
            return user.getReMark();
        }
        return user.getNickName();
    }
//    public static String createNewGroupName(Context context,int groupId){
//        String groupName = "";
//        WeChatDBManager.getInstance WeChatDBManager.getInstance = WeChatDBManager.getInstance();
//
//        Group group = WeChatDBManager.getInstance.getGroupWithUsers(groupId);
//        if (group!= null && group.getUsers()!= null){
//            if (group.getGroupName().contains("、")){
//                List<User> users = group.getUsers();
//                for (User user : users){
//                    groupName = groupName + user.getNickName()+"、";
//                }
//                groupName = groupName.substring(0,
//                        groupName.length() - 1);
//
//                try {
//                    group.setGroupName(groupName);
//                    updateGroupName(context, group, groupName);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//
//
//        }
//
//        return  groupName;
//
//
//    }


    /**
     * 更改群组名
     *
     * @param context
     */

    public static void updateGroupName(final Context context, final Group group,
                                       String groupName) throws JSONException {

        String userid = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String password = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        try {
            groupName = URLEncoder.encode(groupName, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 拼接URL链接
        String userQuitGroupUrl = ROOTURL + "/IMServer/group/updateGroupName?"
                + "userId=" + userid + "&passWord=" + password + "&groupId="
                + group.getGroupId() + "&groupName=" + groupName;
        Log.i("GetHttpUtil", userQuitGroupUrl);

        EFHttpRequest httpRequest = new EFHttpRequest(context);
        httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
            @Override
            public void onRequestSuccess(int arg0, String arg1) {

                String info = null;
                try {
                    info = new JSONObject(arg1).getString("result");
                } catch (JSONException e) {

                    e.printStackTrace();
                }

                if ("success".equals(info)) {

                     WeChatDBManager.getInstance().insertOrUpdateGroup(group);
                } else if ("fail".equals(info)) {

                }
            }

            // HTTP请求失败；
            @Override
            public void onRequestFail(int arg0, String arg1) {
                Toast.makeText(context, "网络出错", Toast.LENGTH_SHORT).show();

            }
        });

        httpRequest.httpGet(userQuitGroupUrl);

    }

    //判断自己在群里是否被禁言
    public static boolean judgeOwnerIsBanSpeakInGroup(int groupId) {
        return judgeUserIsBanSpeakInGroup(groupId, Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));

    }

    public static boolean judgeUserIsBanSpeakInGroup(int groupId, int userId) {
        User user =  WeChatDBManager.getInstance().getGroupUserInfo(groupId, userId);
        if (user == null) {
            return false;
        }
        return user.isGroupBanSpeak();
    }

    //获取用户在群组中的角色
    public static int getUserRoleInGroup(int groupId, int userId) {
        User user =  WeChatDBManager.getInstance().getGroupUserInfo(groupId, userId);
        if (user == null) {
            return 0;
        }
        return user.getGroupUserType();
    }

    //获取用户在群组中的角色
    public static int getOwnerRoleInGroup(int groupId) {
        return getUserRoleInGroup(groupId,
                Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
    }

    //获取用户是否是管理员
    public static boolean userIsManager(int groupId) {
        int role = getUserRoleInGroup(groupId,
                Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        if (role == User.GROUPMEMBER) {
            return false;
        }
        return true;
    }
}
